package com.beidouapp.mvc;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.beidouapp.common.enums.YesNoEnum;
import com.beidouapp.common.util.JSONUtils;
import com.beidouapp.domain.pojo.DrugMsg;
import com.beidouapp.domain.pojo.DrugReference;
import com.beidouapp.domain.pojo.Organization;
import com.beidouapp.domain.vo.OrgRoleEmployeeVO;
import com.beidouapp.security.model.ReturnDataInfo;
import com.beidouapp.security.model.SessionUser;
import com.beidouapp.security.utils.DscpCommUtils;
import com.beidouapp.service.DrugsService;
import com.beidouapp.service.OrganizationService;
import com.beidouapp.util.CommonUtil;

@Controller
@RequestMapping(value = "/drugs")
public class DrugsController {

    private Logger logger = LoggerFactory.getLogger(DrugsController.class);

    @Autowired
    DrugsService drugsService;

    @Autowired
    private OrganizationService organizationService;

    @RequestMapping(value = "/page/list", method = RequestMethod.GET)
    public ModelAndView forward2ManagePage(HttpSession session) {
        ModelAndView view = new ModelAndView();
        view.setViewName("drugs/drugs_list");
        return view;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public @ResponseBody
    ReturnDataInfo<DrugReference> listDrugs(HttpSession session, HttpServletRequest request,
            @RequestParam(value = "iDisplayStart", required = false, defaultValue = "0")
            Integer offset, @RequestParam(value = "iDisplayLength", required = false, defaultValue = "10")
            Integer limit, @RequestParam(value = "globalSearch", required = false, defaultValue = "{}")
            String globalSearch) {
        try {
            Map paramters = new HashMap();
            if (globalSearch != null) {
                JSONObject jsonObject = JSONObject.fromObject(globalSearch);
                paramters.putAll(jsonObject);
            }
            long startTime = System.currentTimeMillis();
            List<DrugReference> drugReferences = drugsService.findDrugsByMap(paramters, offset, limit);
            Integer coInteger = drugsService.findDrugsCountByMap(paramters);
            long endTime = System.currentTimeMillis();
            logger.info("查询药品列表耗时： " + (endTime - startTime) + " ms");
            return ReturnDataInfo.createSuccessfulExecuteResults(drugReferences, offset, limit, coInteger.longValue());
        } catch (Exception ex) {
            logger.error("获取药品列表失败", ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }

    @RequestMapping(value = "/page/add", method = RequestMethod.GET)
    public ModelAndView addDrugsPage(HttpSession session) {
        ModelAndView view = new ModelAndView();
        view.setViewName("drugs/drugs_add");
        return view;
    }

    @RequestMapping(value = "/page/update/{id}", method = RequestMethod.GET)
    public ModelAndView modifyEmpPage(HttpSession session, @PathVariable
    String id) {
        ModelAndView view = new ModelAndView();

        DrugReference drug = drugsService.getDrugDetailById(id);

        view.addObject("drug", drug);
        view.setViewName("drugs/drugs_update");
        return view;
    }

    @RequestMapping(value = "/page/search", method = RequestMethod.GET)
    public ModelAndView search(HttpSession session) {
        ModelAndView view = new ModelAndView();
        view.setViewName("drugs/drugs_search");
        return view;
    }

    @RequestMapping(value = "/searchDrugs/{kw}", method = RequestMethod.GET)
    public ModelAndView searchDrugs(HttpSession session, @PathVariable
    String kw) {
        ModelAndView view = new ModelAndView();
        List<DrugReference> drugReferences = null;
        try {
            kw = URLDecoder.decode(kw, "utf-8").trim();
            drugReferences = drugsService.getDrugReferences(kw);
            System.out.println(drugReferences);
        } catch (Exception e) {

            e.printStackTrace();
        }
        view.addObject("kw", kw);
        view.addObject("drugs", drugReferences);
        view.setViewName("drugs/drugs_result");
        return view;
    }

    @RequestMapping(value = "/saveOrgUpdateDrugs", method = RequestMethod.POST, headers = "Content-Type=application/json")
    public @ResponseBody
    ReturnDataInfo<String> saveOrgUpdateDrugs(HttpSession session, HttpServletRequest request, @RequestBody
    DrugReference drugReference) {
        try {

            drugsService.saveOrgUpdateDrugs(drugReference);
            return ReturnDataInfo.createSuccessfulSingleExecuteResult(null);
        } catch (Exception ex) {
            logger.error("错误：" + ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }

    @RequestMapping(value = "/deleteDrugs/{id}", method = RequestMethod.POST, headers = "Content-Type=application/json")
    public @ResponseBody
    ReturnDataInfo<String> deleteDrugs(@PathVariable
    String id, HttpServletRequest request) {
        try {
            drugsService.deleteDrugs(id);
        } catch (Exception e) {
            logger.error("删除药品对象异常！", e);
            return ReturnDataInfo.createFailedExecuteResult(e.getMessage());
        }
        return ReturnDataInfo.createSuccessfulSingleExecuteResult(null);
    }

    @RequestMapping(value = "/showDrugsDetail/{id}", method = RequestMethod.GET)
    public ModelAndView showDrugsDetail(HttpSession session, @PathVariable
    String id) {
        ModelAndView view = new ModelAndView();
        DrugReference drugReference = drugsService.getDrugDetailById(id);
        DrugMsg drugMsg = new DrugMsg();
        drugMsg.setReferenceId(id);
        List<DrugMsg> drugMsgs = drugsService.getDrugMsgList(drugMsg);
        view.addObject("drug", drugReference);
        view.addObject("drugMsgs", drugMsgs);
        view.setViewName("drugs/drugs_detail");
        return view;
    }

    @RequestMapping(value = "/saveLeaveMsg", method = RequestMethod.POST, headers = "Content-Type=application/json")
    public @ResponseBody
    ReturnDataInfo<String> saveLeaveMsg(HttpSession session, HttpServletRequest request, @RequestBody
    DrugMsg drugMsg) {
        try {
            drugMsg.setIp(CommonUtil.getCLientIp(request));
            drugsService.saveLeaveMsg(drugMsg);
            return ReturnDataInfo.createSuccessfulSingleExecuteResult(null);
        } catch (Exception ex) {
            logger.error("错误：" + ex);
            return ReturnDataInfo.createFailedExecuteResult(ex.getMessage());
        }
    }

}
